<!DOCTYPE HTML>
<html lang="">
<head>
    <!--Setting-->
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
    <meta http-equiv="Cache-Control" content="no-siteapp">
    <meta http-equiv="Cache-Control" content="no-transform">
    <meta name="renderer" content="webkit|ie-comp|ie-stand">
    <meta name="apple-mobile-web-app-capable" content="无限Coding">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="format-detection" content="telephone=no,email=no,adress=no">
    <meta name="browsermode" content="application">
    <meta name="screen-orientation" content="portrait">
    <link rel="dns-prefetch" href="http://yoursite.com">
    <!--SEO-->





<meta name="robots" content="all" />
<meta name="google" content="all" />
<meta name="googlebot" content="all" />
<meta name="verify" content="all" />
    <!--Title-->


<title>超详细遗传算法解析附带TSP代码 | 无限Coding</title>


    <link rel="alternate" href="/atom.xml" title="无限Coding" type="application/atom+xml">


    <link rel="icon" href="/favicon.ico">

    



<link rel="stylesheet" href="//cdn.bootcss.com/bootstrap/3.3.4/css/bootstrap.min.css?rev=3.3.4">
<link rel="stylesheet" href="//cdn.bootcss.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="/css/style.css?rev=@@hash">




    
	<div class="hide">
		<script type="text/javascript">
			var cnzz_protocol = (("https:" == document.location.protocol) ? " https://" : " http://");document.write(unescape("%3Cspan class='cnzz_stat_icon_1263868967 hide' %3E%3Cscript%20src%3D%22https%3A%2F%2Fs95.cnzz.com%2Fz_stat.php%3Fweb_id%3D1272564536%22%3E%3C%2Fscript%3E%3C/span%3E%3Cscript src='" + cnzz_protocol + "s19.cnzz.com/z_stat.php%3Fid%3D1263868967%26show%3Dpic1' type='text/javascript'%3E%3C/script%3E"));
		</script>
	</div>






    
</head>


<!--[if lte IE 8]>
<style>
    html{ font-size: 1em }
</style>
<![endif]-->
<!--[if lte IE 9]>
<div style="ie">你使用的浏览器版本过低，为了你更好的阅读体验，请更新浏览器的版本或者使用其他现代浏览器，比如Chrome、Firefox、Safari等。</div>
<![endif]-->

<body>
    <header class="main-header"  style="background-image:url(http://oyxhmjutw.bkt.clouddn.com/18-2-21/37655074.jpg)"  >
    <div class="main-header-box">
        <a class="header-avatar" href="/" title="">
            <img src="/img/avatar.jpg" alt="logo头像">
        </a>
        <div class="branding">
        	<!--<h2 class="text-hide">Snippet主题,从未如此简单有趣</h2>-->
            
                 <img src="/img/branding.png" alt="Snippet 博客主题">  
             
    	</div>
    </div>
</header>
    <nav class="main-navigation">
    <div class="container">
        <div class="row">
            <div class="col-sm-12">
                <div class="navbar-header"><span class="nav-toggle-button collapsed" data-toggle="collapse" data-target="#main-menu" id="mnav">
                    <span class="sr-only">Toggle navigation</span>
                    <i class="fa fa-bars"></i>
                    </span>
                </div>
                <div class="collapse navbar-collapse" id="main-menu">
                    <ul class="menu">
                        
                            <li role="presentation"><a href="/"><i class="fa fa-fw "></i>首页</a>
                            </li>
                        
                            <li role="presentation"><a href="/"><i class="fa fa-fw "></i>推荐</a>
                            </li>
                        
                            <li role="presentation"><a href="/"><i class="fa fa-fw "></i>资源</a>
                            </li>
                        
                            <li role="presentation"><a href="/"><i class="fa fa-fw "></i>随想</a>
                            </li>
                        
                            <li role="presentation"><a href="/"><i class="fa fa-fw "></i>关于</a>
                            </li>
                        
                    </ul>
                </div>
            </div>
        </div>
    </div>
</nav>
    <section class="content-wrap">
        <div class="container">
            <div class="row">
                <main class="col-md-8 main-content m-post">
                    <p id="process"></p>
<article class="post">
    <div class="post-head">
        <h1 id="超详细遗传算法解析附带TSP代码">
            
	            超详细遗传算法解析附带TSP代码
            
        </h1>
        <div class="post-meta">
    
    
    <span class="categories-meta fa-wrap">
        <i class="fa fa-folder-open-o"></i>
        <a href="/categories/算法">
            算法
        </a>
    </span>
    
    
    <span class="fa-wrap">
        <i class="fa fa-tags"></i>
        <span class="tags-meta">
            
            <a href="/tags/算法">
               算法
            </a>
            
        </span>
    </span>
    
    
    <span class="fa-wrap">
        <i class="fa fa-clock-o"></i>
        <span class="date-meta">2018/05/22</span>
    </span>
</div>

            
            
    </div>
    
    <div class="post-body post-content">
        <h1 id="00-目录"><a href="#00-目录" class="headerlink" title="00 目录"></a>00 目录</h1><ul>
<li>遗传算法定义</li>
<li>生物学术语</li>
<li>问题导入</li>
<li>大体实现</li>
<li>具体细节</li>
<li>代码实现</li>
</ul>
<a id="more"></a>
<h1 id="01-什么是遗传算法？"><a href="#01-什么是遗传算法？" class="headerlink" title="01 什么是遗传算法？"></a>01 什么是遗传算法？</h1><h2 id="1-1-遗传算法的科学定义"><a href="#1-1-遗传算法的科学定义" class="headerlink" title="1.1 遗传算法的科学定义"></a>1.1 遗传算法的科学定义</h2><p>遗传算法（Genetic Algorithm, GA）是模拟达尔文生物进化论的自然选择和遗传学机理的生物进化过程的计算模型，是一种通过模拟自然进化过程搜索最优解的方法。</p>
<p>其主要特点是直接对结构对象进行操作，不存在求导和函数连续性的限定；具有内在的隐并行性和更好的全局寻优能力；采用概率化的寻优方法，不需要确定的规则就能自动获取和指导优化的搜索空间，自适应地调整搜索方向。</p>
<p>遗传算法以一种群体中的所有个体为对象，并利用随机化技术指导对一个被编码的参数空间进行高效搜索。其中，选择、交叉和变异构成了遗传算法的遗传操作；参数编码、初始群体的设定、适应度函数的设计、遗传操作设计、控制参数设定五个要素组成了遗传算法的核心内容。 </p>
<h2 id="1-2-遗传算法的执行过程-参照百度百科"><a href="#1-2-遗传算法的执行过程-参照百度百科" class="headerlink" title="1.2 遗传算法的执行过程(参照百度百科)"></a>1.2 遗传算法的执行过程(参照百度百科)</h2><p>遗传算法是从代表问题可能潜在的解集的一个种群（population）开始的，而一个种群则由经过基因（gene）编码的一定数目的个体(individual)组成。每个个体实际上是染色体(chromosome)带有特征的实体。</p>
<p>染色体作为遗传物质的主要载体，即多个基因的集合，其内部表现（即基因型）是某种基因组合，它决定了个体的形状的外部表现，如黑头发的特征是由染色体中控制这一特征的某种基因组合决定的。因此，在一开始需要实现从表现型到基因型的映射即编码工作。由于仿照基因编码的工作很复杂，我们往往进行简化，如二进制编码。</p>
<p>初代种群产生之后，按照适者生存和优胜劣汰的原理，逐代（generation）演化产生出越来越好的近似解，在每一代，根据问题域中个体的适应度（fitness）大小选择（selection）个体，并借助于自然遗传学的遗传算子（genetic operators）进行组合交叉（crossover）和变异（mutation），产生出代表新的解集的种群。</p>
<p>这个过程将导致种群像自然进化一样的后生代种群比前代更加适应于环境，末代种群中的最优个体经过解码（decoding），可以作为问题近似最优解。</p>
<h2 id="1-3-遗传算法过程图解"><a href="#1-3-遗传算法过程图解" class="headerlink" title="1.3 遗传算法过程图解"></a>1.3 遗传算法过程图解</h2><p><img src="http://oyxhmjutw.bkt.clouddn.com/18-4-28/39149323.jpg" alt=""></p>
<h1 id="02-相关生物学术语"><a href="#02-相关生物学术语" class="headerlink" title="02 相关生物学术语"></a>02 相关生物学术语</h1><p>为了大家更好了解遗传算法，在此之前先简单介绍一下相关生物学术语，大家了解一下即可。</p>
<ul>
<li><p>基因型(genotype)：性状染色体的内部表现；</p>
</li>
<li><p>表现型(phenotype)：染色体决定的性状的外部表现，或者说，根据基因型形成的个体的外部表现；</p>
</li>
<li><p>进化(evolution)：种群逐渐适应生存环境，品质不断得到改良。生物的进化是以种群的形式进行的。</p>
</li>
<li><p>适应度(fitness)：度量某个物种对于生存环境的适应程度。</p>
</li>
<li><p>选择(selection)：以一定的概率从种群中选择若干个个体。一般，选择过程是一种基于适应度的优胜劣汰的过程。</p>
</li>
<li><p>复制(reproduction)：细胞分裂时，遗传物质DNA通过复制而转移到新产生的细胞中，新细胞就继承了旧细胞的基因。</p>
</li>
<li><p>交叉(crossover)：两个染色体的某一相同位置处DNA被切断，前后两串分别交叉组合形成两个新的染色体。也称基因重组或杂交；</p>
</li>
<li><p>变异(mutation)：复制时可能（很小的概率）产生某些复制差错，变异产生新的染色体，表现出新的性状。</p>
</li>
<li><p>编码(coding)：DNA中遗传信息在一个长链上按一定的模式排列。遗传编码可看作从表现型到基因型的映射。</p>
</li>
<li><p>解码(decoding)：基因型到表现型的映射。</p>
</li>
<li><p>个体（individual）：指染色体带有特征的实体；</p>
</li>
<li><p>种群（population）：个体的集合，该集合内个体数称为种群</p>
</li>
</ul>
<h1 id="03-问题引出与解决"><a href="#03-问题引出与解决" class="headerlink" title="03 问题引出与解决"></a>03 问题引出与解决</h1><h2 id="3-1-一元函数最大值问题"><a href="#3-1-一元函数最大值问题" class="headerlink" title="3.1 一元函数最大值问题"></a>3.1 一元函数最大值问题</h2><p> 如下的函数图像：</p>
<p><img src="http://oyxhmjutw.bkt.clouddn.com/18-4-25/29043298.jpg" alt=""></p>
<blockquote>
<p>现在我们要在既定的区间内找出函数的最大值。</p>
</blockquote>
<p>学过高中数学的孩纸都知道，上面的函数存在着很多的极大值和极小值。而最大值则是指定区间的极大值中的最大的那一个。从图像上具体表现为，极大值像是一座座山峰，极小值则是像一座座山谷。因此，我们也可以把遗传算法的过程看作是一个在多元函数里面求最优解的过程。</p>
<p>这些山峰对应着局部最优解，其中有一个山峰是海拔最高的，这个山峰则对应的是全局最优解。那么，遗传算法要做的就是尽量爬到最高峰，而不是困在较低的小山峰上。（如果问题求解是最小值，那么要做的就是尽量走到最低谷，道理是一样的）。</p>
<p><img src="http://oyxhmjutw.bkt.clouddn.com/18-4-25/3675000.jpg" alt=""></p>
<h2 id="3-2-“袋鼠蹦跳”"><a href="#3-2-“袋鼠蹦跳”" class="headerlink" title="3.2 “袋鼠蹦跳”"></a>3.2 “袋鼠蹦跳”</h2><p>既然我们把函数曲线理解成一个一个山峰和山谷组成的山脉。那么我们可以设想所得到的每一个解就是一只袋鼠，我们希望它们不断的向着更高处跳去，直到跳到最高的山峰。<strong>所以求最大值的过程就转化成一个“袋鼠跳”的过程。</strong></p>
<p>下面介绍介绍“袋鼠跳”的几种方式。</p>
<ul>
<li><p>爬山算法：一只袋鼠朝着比现在高的地方跳去。它找到了不远处的最高的山峰。但是这座山不一定是最高峰。这就是爬山算法，它不能保证局部最优值就是全局最优值。</p>
</li>
<li><p>模拟退火：袋鼠喝醉了。它随机地跳了很长时间。这期间，它可能走向高处，也可能踏入平地。但是，它渐渐清醒了并朝最高峰跳去。这就是模拟退火算法。</p>
</li>
<li><p>遗传算法：有很多袋鼠，它们降落到喜玛拉雅山脉的任意地方。这些袋鼠并不知道它们的任务是寻找珠穆朗玛峰。但每过几年，就在一些海拔高度较低的地方射杀一些袋鼠。于是，不断有袋鼠死于海拔较低的地方，而越是在海拔高的袋鼠越是能活得更久，也越有机会生儿育女。就这样经过许多年，这些袋鼠们竟然都不自觉地聚拢到了一个个的山峰上，可是在所有的袋鼠中，只有聚拢到珠穆朗玛峰的袋鼠被带回了美丽的澳洲。</p>
</li>
</ul>
<h1 id="04-大体实现过程"><a href="#04-大体实现过程" class="headerlink" title="04 大体实现过程"></a>04 大体实现过程</h1><p>遗传算法中每一条染色体，对应着遗传算法的一个解决方案，一般我们用适应性函数（fitness function）来衡量这个解决方案的优劣。所以从一个基因组到其解的适应度形成一个映射。<strong>遗传算法的实现过程实际上就像自然界的进化过程那样。</strong></p>
<p>下面我们用袋鼠跳中的步骤一一对应解释，以方便大家理解：</p>
<p>1) 首先寻找一种对问题潜在解进行“数字化”编码的方案。（建立表现型和基因型的映射关系）</p>
<p>2) 随机初始化一个种群（那么第一批袋鼠就被随意地分散在山脉上），种群里面的个体就是这些数字化的编码。</p>
<p>3) 接下来，通过适当的解码过程之后（得到袋鼠的位置坐标）。</p>
<p>4) 用适应性函数对每一个基因个体作一次适应度评估（袋鼠爬得越高当然就越好，所以适应度相应越高）。</p>
<p>5) 用选择函数按照某种规定择优选择（每隔一段时间，射杀一些所在海拔较低的袋鼠，以保证袋鼠总体数目持平。）。</p>
<p>6) 让个体基因变异（让袋鼠随机地跳一跳）。</p>
<p>7) 然后产生子代（希望存活下来的袋鼠是多产的，并在那里生儿育女）。</p>
<p><strong>遗传算法并不保证你能获得问题的最优解，但是使用遗传算法的最大优点在于你不必去了解和操心如何去“找”最优解。（你不必去指导袋鼠向那边跳，跳多远。）而只要简单的“否定”一些表现不好的个体就行了。（把那些总是爱走下坡路的袋鼠射杀，这就是遗传算法的精粹！）</strong></p>
<p>由此我们可以得出遗传算法的一般步骤：</p>
<p>1) 随机产生种群。<br>2) 根据策略判断个体的适应度，是否符合优化准则，若符合，输出最佳个体及其最优解，结束。否则，进行下一步。<br>3) 依据适应度选择父母，适应度高的个体被选中的概率高，适应度低的个体被淘汰。<br>4) 用父母的染色体按照一定的方法进行交叉，生成子代。<br>5) 对子代染色体进行变异。</p>
<p><strong>由交叉和变异产生新一代种群，返回步骤2，直到最优解产生。</strong></p>
<p>具体图解可以回到1.3查看。</p>
<h1 id="05-开始我们的进化-具体实现细节"><a href="#05-开始我们的进化-具体实现细节" class="headerlink" title="05 开始我们的进化(具体实现细节)"></a>05 开始我们的进化(具体实现细节)</h1><h2 id="5-1-先从编码说起"><a href="#5-1-先从编码说起" class="headerlink" title="5.1 先从编码说起"></a>5.1 先从编码说起</h2><p>编码是应用遗传算法时要解决的首要问题，也是设计遗传算法时的一个关键步骤。编码方法影响到交叉算子、变异算子等遗传算子的运算方法，大很大程度上决定了遗传进化的效率。</p>
<p>迄今为止人们已经提出了许多种不同的编码方法。总的来说，这些编码方法可以分为三大类：二进制编码法、浮点编码法、符号编码法。下面分别进行介绍：</p>
<h3 id="5-1-1-二进制编码法"><a href="#5-1-1-二进制编码法" class="headerlink" title="5.1.1 二进制编码法"></a>5.1.1 二进制编码法</h3><p>就像人类的基因有AGCT 4种碱基序列一样。不过在这里我们只用了0和1两种碱基,然后将他们串成一条链形成染色体。一个位能表示出2种状态的信息量，因此足够长的二进制染色体便能表示所有的特征。这便是二进制编码。如下：<br>1110001010111</p>
<p>它由二进制符号0和1所组成的二值符号集。它有以下一些优点：</p>
<p>1) 编码、解码操作简单易行<br>2) 交叉、变异等遗传操作便于实现<br>3) 合最小字符集编码原则<br>4) 利用模式定理对算法进行理论分析。</p>
<p>二进制编码的缺点是：对于一些连续函数的优化问题，由于其随机性使得其局部搜索能力较差，如对于一些高精度的问题（如上题），当解迫近于最优解后，由于其变异后表现型变化很大，不连续，所以会远离最优解，达不到稳定。</p>
<h3 id="5-1-２-浮点编码法"><a href="#5-1-２-浮点编码法" class="headerlink" title="5.1.２ 浮点编码法"></a>5.1.２ 浮点编码法</h3><p>二进制编码虽然简单直观，但明显地。但是存在着连续函数离散化时的映射误差。个体长度较短时，可能达不到精度要求，而个体编码长度较长时，虽然能提高精度，但增加了解码的难度，使遗传算法的搜索空间急剧扩大。</p>
<p> 所谓浮点法，是指个体的每个基因值用某一范围内的一个浮点数来表示。在浮点数编码方法中，必须保证基因值在给定的区间限制范围内，遗传算法中所使用的交叉、变异等遗传算子也必须保证其运算结果所产生的新个体的基因值也在这个区间限制范围内。如下所示：</p>
<p> 1.2-3.2-5.3-7.2-1.4-9.7</p>
<p> 浮点数编码方法有下面几个优点：</p>
<p>1) 适用于在遗传算法中表示范围较大的数<br>2) 适用于精度要求较高的遗传算法<br>3) 便于较大空间的遗传搜索<br>4) 改善了遗传算法的计算复杂性，提高了运算交率<br>5) 便于遗传算法与经典优化方法的混合使用<br>6) 便于设计针对问题的专门知识的知识型遗传算子<br>7) 便于处理复杂的决策变量约束条件</p>
<h3 id="5-1-3-符号编码法"><a href="#5-1-3-符号编码法" class="headerlink" title="5.1.3 符号编码法"></a>5.1.3 符号编码法</h3><p>符号编码法是指个体染色体编码串中的基因值取自一个无数值含义、而只有代码含义的符号集如｛A,B,C…｝。<br>符号编码的主要优点是：</p>
<p>1) 符合有意义积术块编码原则<br>2) 便于在遗传算法中利用所求解问题的专门知识<br>3) 便于遗传算法与相关近似算法之间的混合使用。</p>
<h2 id="5-2-为我们的袋鼠染色体编码"><a href="#5-2-为我们的袋鼠染色体编码" class="headerlink" title="5.2 为我们的袋鼠染色体编码"></a>5.2 为我们的袋鼠染色体编码</h2><p>在上面介绍了一系列编码方式以后，那么，如何利用上面的编码来为我们的袋鼠染色体编码呢？首先我们要明确一点：编码无非就是建立从基因型到表现型的映射关系。这里的表现型可以理解为个体特征（比如身高、体重、毛色等等）。那么，在此问题下，我们关心的个体特征就是：袋鼠的位置坐标（因为我们要把海拔低的袋鼠给杀掉）。无论袋鼠长什么样，爱吃什么。我们关心的始终是袋鼠在哪里，并且只要知道了袋鼠的位置坐标（位置坐标就是相应的染色体编码，可以通过解码得出），我们就可以：</p>
<p>1) 在喜马拉雅山脉的地图上找到相应的位置坐标，算出海拔高度。（相当于通过自变量求得适应函数的值）然后判读该不该射杀该袋鼠。<br>2) 可以知道染色体交叉和变异后袋鼠新的位置坐标。</p>
<p>回到3.1中提的求一元函数最大值的问题。在上面我们把极大值比喻为山峰，那么，袋鼠的位置坐标可以比喻为区间[-1, 2]的某一个x坐标（有了x坐标，再通过函数表达式可以算出函数值 &lt;==&gt; 得到了袋鼠染色体编码，解码得到位置坐标，在喜马拉雅山脉地图查询位置坐标算出海拔高度）。这个x坐标是一个实数，现在，说白了就是怎么对这个x坐标进行编码。下面我们以二进制编码为例讲解，不过这种情况下以二进制编码比较复杂就是了。（如果以浮点数编码，其实就很简洁了，就一浮点数而已。）</p>
<p>我们说过，一定长度的二进制编码序列，只能表示一定精度的浮点数。在这里假如我们要求解精确到六位小数，由于区间长度为2 - (-1) = 3 ,为了保证精度要求，至少把区间[-1,2]分为3 × 10^6等份。又因为</p>
<blockquote>
<p>2^21 = 2097152 &lt; 3*10^6 &lt; 2^22 = 4194304</p>
</blockquote>
<p>所以编码的二进制串至少需要22位。</p>
<p><strong>把一个二进制串(b0,b1,….bn)转化为区间里面对应的实数值可以通过下面两个步骤：</strong></p>
<p>1) 将一个二进制串代表的二进制数转化为10进制数：</p>
<p><img src="http://oyxhmjutw.bkt.clouddn.com/18-4-28/19594055.jpg" alt="">  </p>
<p>2) 对应区间内的实数：</p>
<p><img src="http://oyxhmjutw.bkt.clouddn.com/18-4-28/77256389.jpg" alt=""></p>
<p>例如一个二进制串(1000101110110101000111)2通过上面换算以后，表示实数值0.637197。</p>
<p>好了，上面的编码方式只是举个例子让大家更好理解而已，编码的方式千奇百怪，层出不穷，每个问题可能采用的编码方式都不一样。在这一点上大家要注意。</p>
<h2 id="5-3-评价个体的适应度–适应度函数（fitness-function）"><a href="#5-3-评价个体的适应度–适应度函数（fitness-function）" class="headerlink" title="5.3 评价个体的适应度–适应度函数（fitness function）"></a>5.3 评价个体的适应度–适应度函数（fitness function）</h2><p>前面说了，适应度函数主要是通过个体特征从而判断个体的适应度。在本例的袋鼠跳中，我们只关心袋鼠的海拔高度，以此来判断是否该射杀该袋鼠。这样一来，该函数就非常简单了。只要输入袋鼠的位置坐标，在通过相应查找运算，返回袋鼠当前位置的海拔高度就行。</p>
<p>适应度函数也称评价函数，是根据目标函数确定的用于区分群体中个体好坏的标准。适应度函数总是非负的，而目标函数可能有正有负，故需要在目标函数与适应度函数之间进行变换。</p>
<p>评价个体适应度的一般过程为：</p>
<ol>
<li><p>对个体编码串进行解码处理后，可得到个体的表现型。</p>
</li>
<li><p>由个体的表现型可计算出对应个体的目标函数值。</p>
</li>
<li><p>根据最优化问题的类型，由目标函数值按一定的转换规则求出个体的适应度。</p>
</li>
</ol>
<h2 id="5-4-射杀一些袋鼠–选择函数（selection）"><a href="#5-4-射杀一些袋鼠–选择函数（selection）" class="headerlink" title="5.4 射杀一些袋鼠–选择函数（selection）"></a>5.4 射杀一些袋鼠–选择函数（selection）</h2><p>遗传算法中的选择操作就是用来确定如何从父代群体中按某种方法选取那些个体，以便遗传到下一代群体。选择操作用来确定重组或交叉个体，以及被选个体将产生多少个子代个体。前面说了，我们希望海拔高的袋鼠存活下来，并尽可能繁衍更多的后代。但我们都知道，在自然界中，适应度高的袋鼠越能繁衍后代，但这也是从概率上说的而已。毕竟有些适应度低的袋鼠也可能逃过我们的眼睛。</p>
<p>那么，怎么建立这种概率关系呢？</p>
<p><strong>下面介绍几种常用的选择算子：</strong></p>
<ol>
<li><p>轮盘赌选择（Roulette Wheel Selection）：是一种回放式随机采样方法。每个个体进入下一代的概率等于它的适应度值与整个种群中个体适应度值和的比例。选择误差较大。</p>
</li>
<li><p>随机竞争选择（Stochastic Tournament）：每次按轮盘赌选择一对个体，然后让这两个个体进行竞争，适应度高的被选中，如此反复，直到选满为止。</p>
</li>
<li><p>最佳保留选择：首先按轮盘赌选择方法执行遗传算法的选择操作，然后将当前群体中适应度最高的个体结构完整地复制到下一代群体中。</p>
</li>
<li><p>无回放随机选择（也叫期望值选择Excepted Value Selection）：根据每个个体在下一代群体中的生存期望来进行随机选择运算。方法如下:</p>
<p> （1） 计算群体中每个个体在下一代群体中的生存期望数目N。</p>
<p> （2） 若某一个体被选中参与交叉运算，则它在下一代中的生存期望数目减去0.5，若某一个体未   被选中参与交叉运算，则它在下一代中的生存期望数目减去1.0。</p>
<p> （3） 随着选择过程的进行，若某一个体的生存期望数目小于0时，则该个体就不再有机会被选中。</p>
</li>
<li><p>确定式选择：按照一种确定的方式来进行选择操作。具体操作过程如下：</p>
<p> （1） 计算群体中各个个体在下一代群体中的期望生存数目N。</p>
<p> （2） 用N的整数部分确定各个对应个体在下一代群体中的生存数目。</p>
<p> （3） 用N的小数部分对个体进行降序排列，顺序取前M个个体加入到下一代群体中。至此可完全确定出下一代群体中Ｍ个个体。</p>
</li>
<li><p>无回放余数随机选择：可确保适应度比平均适应度大的一些个体能够被遗传到下一代群体中，因而选择误差比较小。</p>
</li>
<li><p>均匀排序：对群体中的所有个体按期适应度大小进行排序，基于这个排序来分配各个个体被选中的概率。</p>
</li>
<li><p>最佳保存策略：当前群体中适应度最高的个体不参与交叉运算和变异运算，而是用它来代替掉本代群体中经过交叉、变异等操作后所产生的适应度最低的个体。</p>
</li>
<li><p>随机联赛选择：每次选取几个个体中适应度最高的一个个体遗传到下一代群体中。</p>
</li>
<li><p>排挤选择：新生成的子代将代替或排挤相似的旧父代个体，提高群体的多样性。</p>
</li>
</ol>
<p>下面以轮盘赌选择为例给大家讲解一下：</p>
<p>假如有５条染色体，他们的适应度分别为５、８、３、７、２。</p>
<p>那么总的适应度为：F = 5 + 8 + 3 + 7 + 2 = 25。</p>
<p>那么各个个体的被选中的概率为：</p>
<p>α1 = ( 5 / 25 ) * 100% = 20%</p>
<p>α2 = ( 8 / 25 ) * 100% = 32%</p>
<p>α3 = ( 3 / 25 ) * 100% = 12%</p>
<p>α4 = ( 7 / 25 ) * 100% = 28%</p>
<p>α5 = ( 2 / 25 ) * 100% = 8%</p>
<p>所以转盘如下：</p>
<p><img src="http://oyxhmjutw.bkt.clouddn.com/18-4-28/43992624.jpg" alt=""></p>
<p>当指针在这个转盘上转动，停止下来时指向的个体就是天选之人啦。可以看出，适应性越高的个体被选中的概率就越大。</p>
<h2 id="5-５-遗传–染色体交叉-crossover"><a href="#5-５-遗传–染色体交叉-crossover" class="headerlink" title="5.５ 遗传–染色体交叉(crossover)"></a>5.５ 遗传–染色体交叉(crossover)</h2><p>遗传算法的交叉操作，是指对两个相互配对的染色体按某种方式相互交换其部分基因，从而形成两个新的个体。</p>
<p>适用于二进制编码个体或浮点数编码个体的交叉算子：</p>
<ol>
<li><p>单点交叉（One-point Crossover）：指在个体编码串中只随机设置一个交叉点，然后再该点相互交换两个配对个体的部分染色体。</p>
</li>
<li><p>两点交叉与多点交叉：</p>
<p> (1) 两点交叉（Two-point Crossover）：在个体编码串中随机设置了两个交叉点，然后再进行部分基因交换。</p>
<p> (2) 多点交叉（Multi-point Crossover）</p>
</li>
<li><p>均匀交叉（也称一致交叉，Uniform Crossover）：两个配对个体的每个基因座上的基因都以相同的交叉概率进行交换，从而形成两个新个体。</p>
</li>
<li><p>算术交叉（Arithmetic Crossover）：由两个个体的线性组合而产生出两个新的个体。该操作对象一般是由浮点数编码表示的个体。</p>
</li>
</ol>
<p>咳咳，根据国际惯例。还是抓一个最简单的二进制单点交叉为例来给大家讲解讲解。</p>
<p>二进制编码的染色体交叉过程非常类似高中生物中所讲的同源染色体的联会过程――随机把其中几个位于同一位置的编码进行交换，产生新的个体。</p>
<p><img src="http://oyxhmjutw.bkt.clouddn.com/18-4-28/91898863.jpg" alt=""></p>
<p>对应的二进制交叉：</p>
<p><img src="http://oyxhmjutw.bkt.clouddn.com/18-4-28/58819951.jpg" alt=""></p>
<h2 id="5-6-变异–基因突变-Mutation"><a href="#5-6-变异–基因突变-Mutation" class="headerlink" title="5.6 变异–基因突变(Mutation)"></a>5.6 变异–基因突变(Mutation)</h2><p>遗传算法中的变异运算，是指将个体染色体编码串中的某些基因座上的基因值用该基因座上的其它等位基因来替换，从而形成新的个体。</p>
<p>例如下面这串二进制编码：</p>
<p>101101001011001</p>
<p>经过基因突变后，可能变成以下这串新的编码：</p>
<p><strong>0</strong>011010<strong>1</strong>1011001</p>
<p>以下变异算子适用于二进制编码和浮点数编码的个体：</p>
<ol>
<li><p>基本位变异（Simple Mutation）：对个体编码串中以变异概率、随机指定的某一位或某几位仅因座上的值做变异运算。</p>
</li>
<li><p>均匀变异（Uniform Mutation）：分别用符合某一范围内均匀分布的随机数，以某一较小的概率来替换个体编码串中各个基因座上的原有基因值。（特别适用于在算法的初级运行阶段）</p>
</li>
<li><p>边界变异（Boundary Mutation）：随机的取基因座上的两个对应边界基因值之一去替代原有基因值。特别适用于最优点位于或接近于可行解的边界时的一类问题。</p>
</li>
<li><p>非均匀变异：对原有的基因值做一随机扰动，以扰动后的结果作为变异后的新基因值。对每个基因座都以相同的概率进行变异运算之后，相当于整个解向量在解空间中作了一次轻微的变动。</p>
</li>
<li><p>高斯近似变异：进行变异操作时用符号均值为Ｐ的平均值，方差为P**2的正态分布的一个随机数来替换原有的基因值。</p>
</li>
</ol>
<h1 id="06-代码实现环节"><a href="#06-代码实现环节" class="headerlink" title="06 代码实现环节"></a>06 代码实现环节</h1><p>好了，上面我们介绍了一大截具体原理。现在就是把各个具体的零部件组装起来，动手写我们的代码了。</p>
<p>代码说明</p>
<p>遗传算法解决TSP旅行商问题</p>
<p>算法分为4个类：</p>
<ul>
<li><p>GeneticAlgorithm</p>
</li>
<li><p>SpeciesIndividual</p>
</li>
<li><p>SpeciesPopulation</p>
</li>
<li><p>TSPData</p>
</li>
</ul>
<p>数据规模: 10 cities, 20 cities and 31 cities.</p>
<p>类说明：</p>
<ul>
<li><p>GeneticAlgorithm:    遗传算法的主体部分，包括选择、交叉、变异</p>
</li>
<li><p>SpeciesIndividual:    物种个体类</p>
</li>
<li><p>SpeciesPopulation:  物种种群类</p>
</li>
<li><p>TSPData：                TSP数据类</p>
</li>
<li><p>MainRun：                主函数运行类</p>
</li>
</ul>
<p>运行平台：</p>
<p>eclipse + windows10</p>
<p><img src="http://oyxhmjutw.bkt.clouddn.com/18-5-11/55072284.jpg" alt=""></p>
<p>详细代码</p>
<p>MainRun.java</p>
<p>主函数运行类，也就是程序入口。在这里创建算法类，创建种群，并开始运行我们的算法。得出结果以后，打印出来。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> GeneticTSP;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 主函数运行类</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MainRun</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// TODO Auto-generated method stub</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">//创建遗传算法驱动对象</span></span><br><span class="line">        GeneticAlgorithm GA=<span class="keyword">new</span> GeneticAlgorithm();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//创建初始种群</span></span><br><span class="line">        SpeciesPopulation speciesPopulation = <span class="keyword">new</span> SpeciesPopulation();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//开始遗传算法（选择算子、交叉算子、变异算子）</span></span><br><span class="line">        SpeciesIndividual bestRate=GA.run(speciesPopulation);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//打印路径与最短距离</span></span><br><span class="line">        bestRate.printRate();</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>TSPData.java</strong></p>
<p>测试数据类，在这里做城市坐标数据等的输入。我直接写死在程序里了，有需要的朋友直接改动一下做一个IO就差不多了。disMap城市距离矩阵，记录各个城市间的距离。比如disMap[i][j]就是城市i和城市j之间的距离。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> GeneticTSP;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * TSP数据类</span></span><br><span class="line"><span class="comment"> * 包含：</span></span><br><span class="line"><span class="comment"> *         disMap 各个城市间距离矩阵</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">TSPData</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">int</span> CITY_NUM; <span class="comment">//城市数</span></span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">int</span> SPECIES_NUM=<span class="number">200</span>; <span class="comment">//种群数</span></span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">int</span> DEVELOP_NUM=<span class="number">1000</span>; <span class="comment">//进化代数</span></span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">float</span> pcl=<span class="number">0.6f</span>,pch=<span class="number">0.95f</span>;<span class="comment">//交叉概率</span></span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">float</span> pm=<span class="number">0.4f</span>;<span class="comment">//变异概率</span></span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">float</span>[][] disMap; <span class="comment">//地图数据</span></span><br><span class="line">    <span class="keyword">static</span></span><br><span class="line">    &#123;</span><br><span class="line"><span class="comment">//        int[][] cityPosition=&#123;</span></span><br><span class="line"><span class="comment">//                &#123;0,0&#125;,&#123;12,32&#125;,&#123;5,25&#125;,&#123;8,45&#125;,&#123;33,17&#125;,</span></span><br><span class="line"><span class="comment">//                &#123;25,7&#125;,&#123;15,15&#125;,&#123;15,25&#125;,&#123;25,15&#125;,&#123;41,12&#125;&#125;;//10个城市（最优解:147）</span></span><br><span class="line"><span class="comment">//        int[][] cityPosition=&#123;</span></span><br><span class="line"><span class="comment">//                &#123;60,200&#125;,&#123;180,200&#125;,&#123;80,180&#125;,&#123;140,180&#125;,</span></span><br><span class="line"><span class="comment">//                &#123;20,160&#125;,&#123;100,160&#125;,&#123;200,160&#125;,&#123;140,140&#125;,</span></span><br><span class="line"><span class="comment">//                &#123;40,120&#125;,&#123;100,120&#125;,&#123;180,100&#125;,&#123;60,80&#125;,</span></span><br><span class="line"><span class="comment">//                &#123;120,80&#125;,&#123;180,60&#125;,&#123;20,40&#125;,&#123;100,40&#125;,</span></span><br><span class="line"><span class="comment">//                &#123;200,40&#125;,&#123;20,20&#125;,&#123;60,20&#125;,&#123;160,20&#125;&#125;;//20个城市（最优解:870）</span></span><br><span class="line"><span class="comment">//        </span></span><br><span class="line">        <span class="comment">//城市坐标集合</span></span><br><span class="line">        <span class="keyword">int</span>[][] cityPosition=&#123;</span><br><span class="line">                &#123;<span class="number">1304</span>,        <span class="number">2312</span>&#125;,&#123;<span class="number">3639</span>,        <span class="number">1315</span>&#125;,         </span><br><span class="line">                &#123;<span class="number">4177</span>,        <span class="number">2244</span>&#125;,&#123;<span class="number">3712</span>,        <span class="number">1399</span>&#125;,            </span><br><span class="line">                &#123;<span class="number">3488</span>,        <span class="number">1535</span>&#125;,&#123;<span class="number">3326</span>,        <span class="number">1556</span>&#125;,         </span><br><span class="line">                &#123;<span class="number">3238</span>,        <span class="number">1229</span>&#125;,&#123;<span class="number">4196</span>,        <span class="number">1004</span>&#125;,         </span><br><span class="line">                &#123;<span class="number">4312</span>,         <span class="number">790</span>&#125;,&#123;<span class="number">4386</span>,         <span class="number">570</span>&#125;,</span><br><span class="line">                &#123;<span class="number">3007</span>,        <span class="number">1970</span>&#125;,&#123;<span class="number">2562</span>,        <span class="number">1756</span>&#125;,</span><br><span class="line">                &#123;<span class="number">2788</span>,        <span class="number">1491</span>&#125;,&#123;<span class="number">2381</span>,        <span class="number">1676</span>&#125;,</span><br><span class="line">                &#123;<span class="number">1332</span>,         <span class="number">695</span>&#125;,&#123;<span class="number">3715</span>,        <span class="number">1678</span>&#125;,</span><br><span class="line">                &#123;<span class="number">3918</span>,        <span class="number">2179</span>&#125;,&#123;<span class="number">4061</span>,        <span class="number">2370</span>&#125;,</span><br><span class="line">                &#123;<span class="number">3780</span>,        <span class="number">2212</span>&#125;,&#123;<span class="number">3676</span>,        <span class="number">2578</span>&#125;,</span><br><span class="line">                &#123;<span class="number">4029</span>,        <span class="number">2838</span>&#125;,&#123;<span class="number">4263</span>,        <span class="number">2931</span>&#125;,</span><br><span class="line">                &#123;<span class="number">3429</span>,        <span class="number">1908</span>&#125;,&#123;<span class="number">3507</span>,        <span class="number">2367</span>&#125;,</span><br><span class="line">                &#123;<span class="number">3394</span>,        <span class="number">2643</span>&#125;,&#123;<span class="number">3439</span>,        <span class="number">3201</span>&#125;,</span><br><span class="line">                &#123;<span class="number">2935</span>,        <span class="number">3240</span>&#125;,&#123;<span class="number">3140</span>,        <span class="number">3550</span>&#125;,</span><br><span class="line">                &#123;<span class="number">2545</span>,        <span class="number">2357</span>&#125;,&#123;<span class="number">2778</span>,        <span class="number">2826</span>&#125;,</span><br><span class="line">                &#123;<span class="number">2370</span>,        <span class="number">2975</span>&#125;&#125;;<span class="comment">//31个城市（最优解:14700）</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">//路径集合</span></span><br><span class="line">        CITY_NUM=cityPosition.length;</span><br><span class="line">        disMap=<span class="keyword">new</span> <span class="keyword">float</span>[CITY_NUM][CITY_NUM];</span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">0</span>;i&lt;CITY_NUM;i++)</span><br><span class="line">        &#123;</span><br><span class="line">            <span class="keyword">for</span>(<span class="keyword">int</span> j=i;j&lt;CITY_NUM;j++)</span><br><span class="line">            &#123;</span><br><span class="line">                <span class="keyword">float</span> dis=(<span class="keyword">float</span>)Math.sqrt(Math.pow((cityPosition[i][<span class="number">0</span>] - cityPosition[j][<span class="number">0</span>]),<span class="number">2</span>) + Math.pow((cityPosition[i][<span class="number">1</span>] - cityPosition[j][<span class="number">1</span>]),<span class="number">2</span>));</span><br><span class="line"></span><br><span class="line">                disMap[i][j]=dis;</span><br><span class="line">                disMap[j][i]=disMap[i][j];</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;   </span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p><strong>SpeciesIndividual.java</strong></p>
<p>物种个体类，每一个个体的染色体对应着一个解决方案。下面做几点说明：</p>
<p>基因：这里要解决的是TSP问题，因此我们直接采用城市序列作为基因的编码。染色体由随机排列的基因组成。</p>
<p>物种适应度：我们说了，物种适应度是评判物种个体的好坏的一个标准。那么，对于TSP问题，解决方案的总距离越小当然就越好了。因此我们直接用了总距离的倒数作为物种适应度。那么，总距离越小，物种适应度相应就越大了。</p>
<p>最后再加一个打印解决方案的方法，就是把城市排列输出来。至于贪婪法生成基因，大家了解一下，这里不做介绍。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> GeneticTSP;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.Random;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 个体类</span></span><br><span class="line"><span class="comment"> * 包含：</span></span><br><span class="line"><span class="comment"> *         1.createByRandomGenes 初始物种基因(随机) 基因直接用城市序列编码</span></span><br><span class="line"><span class="comment"> *         2.calFitness 计算物种适应度</span></span><br><span class="line"><span class="comment"> *         3.printRate 打印路径</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SpeciesIndividual</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    String[] genes;<span class="comment">//基因序列</span></span><br><span class="line">    <span class="keyword">float</span> distance;<span class="comment">//路程</span></span><br><span class="line">    <span class="keyword">float</span> fitness;<span class="comment">//适应度</span></span><br><span class="line">    SpeciesIndividual next;</span><br><span class="line">    <span class="keyword">float</span> rate;</span><br><span class="line"></span><br><span class="line">    SpeciesIndividual()</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="comment">//初始化</span></span><br><span class="line">        <span class="keyword">this</span>.genes=<span class="keyword">new</span> String[TSPData.CITY_NUM];</span><br><span class="line">        <span class="keyword">this</span>.fitness=<span class="number">0.0f</span>;</span><br><span class="line">        <span class="keyword">this</span>.distance=<span class="number">0.0f</span>;</span><br><span class="line">        <span class="keyword">this</span>.next=<span class="keyword">null</span>;</span><br><span class="line">        rate=<span class="number">0.0f</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//初始物种基因(随机)</span></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">createByRandomGenes</span><span class="params">()</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="comment">//初始化基因为1-CITY_NUM序列</span></span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">int</span> i = <span class="number">0</span>;i &lt; genes.length;i++)</span><br><span class="line">        &#123;</span><br><span class="line">            genes[i]=Integer.toString(i+<span class="number">1</span>);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//获取随机种子</span></span><br><span class="line">        Random rand=<span class="keyword">new</span> Random();</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">int</span> j=<span class="number">0</span>;j&lt;genes.length;j++)</span><br><span class="line">        &#123;</span><br><span class="line">            <span class="keyword">int</span> num= j + rand.nextInt(genes.length-j);</span><br><span class="line"></span><br><span class="line">            <span class="comment">//交换</span></span><br><span class="line">            String tmp;</span><br><span class="line">            tmp=genes[num];</span><br><span class="line">            genes[num]=genes[j];</span><br><span class="line">            genes[j]=tmp;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//初始物种基因(贪婪)</span></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">createByGreedyGenes</span><span class="params">()</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        Random rand=<span class="keyword">new</span> Random();</span><br><span class="line">        <span class="keyword">int</span> i= rand.nextInt(TSPData.CITY_NUM); <span class="comment">//随机产生一个城市作为起点</span></span><br><span class="line">        genes[<span class="number">0</span>]=Integer.toString(i+<span class="number">1</span>);</span><br><span class="line">        <span class="keyword">int</span> j;<span class="comment">//终点</span></span><br><span class="line">        <span class="keyword">int</span> cityNum=<span class="number">0</span>;</span><br><span class="line">        <span class="keyword">do</span></span><br><span class="line">        &#123;</span><br><span class="line">            cityNum++;</span><br><span class="line"></span><br><span class="line">            <span class="comment">//选出单源最短城市</span></span><br><span class="line">            <span class="keyword">float</span> minDis=Integer.MAX_VALUE;</span><br><span class="line">            <span class="keyword">int</span> minCity=<span class="number">0</span>;</span><br><span class="line">            <span class="keyword">for</span>(j=<span class="number">0</span>;j&lt;TSPData.CITY_NUM;j++)</span><br><span class="line">            &#123;</span><br><span class="line">                <span class="keyword">if</span>(j != i)</span><br><span class="line">                &#123;</span><br><span class="line">                    <span class="comment">//判是否和已有重复</span></span><br><span class="line">                    <span class="keyword">boolean</span> repeat=<span class="keyword">false</span>;</span><br><span class="line">                    <span class="keyword">for</span>(<span class="keyword">int</span> n=<span class="number">0</span>;n&lt;cityNum;n++)</span><br><span class="line">                    &#123;</span><br><span class="line">                        <span class="keyword">if</span>(Integer.parseInt(genes[n]) == j+<span class="number">1</span>)</span><br><span class="line">                        &#123;</span><br><span class="line">                            repeat=<span class="keyword">true</span>;<span class="comment">//重了</span></span><br><span class="line">                            <span class="keyword">break</span>;</span><br><span class="line">                        &#125;</span><br><span class="line">                    &#125;</span><br><span class="line">                    <span class="keyword">if</span>(repeat == <span class="keyword">false</span>)<span class="comment">//没重</span></span><br><span class="line">                    &#123;</span><br><span class="line">                        <span class="comment">//判长度</span></span><br><span class="line">                        <span class="keyword">if</span>(TSPData.disMap[i][j] &lt; minDis)</span><br><span class="line">                        &#123;</span><br><span class="line">                            minDis=TSPData.disMap[i][j];</span><br><span class="line">                            minCity=j;</span><br><span class="line">                        &#125;</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="comment">//加入到染色体</span></span><br><span class="line">            genes[cityNum]=Integer.toString(minCity+<span class="number">1</span>);</span><br><span class="line">            i=minCity;</span><br><span class="line">        &#125;<span class="keyword">while</span>(cityNum &lt; TSPData.CITY_NUM-<span class="number">1</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//计算物种适应度</span></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">calFitness</span><span class="params">()</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">float</span> totalDis=<span class="number">0.0f</span>;</span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">int</span> i = <span class="number">0</span>;i &lt; TSPData.CITY_NUM;i++)</span><br><span class="line">        &#123;</span><br><span class="line">            <span class="keyword">int</span> curCity=Integer.parseInt(<span class="keyword">this</span>.genes[i])-<span class="number">1</span>;</span><br><span class="line">            <span class="keyword">int</span> nextCity=Integer.parseInt(<span class="keyword">this</span>.genes[(i+<span class="number">1</span>) % TSPData.CITY_NUM])-<span class="number">1</span>;</span><br><span class="line"></span><br><span class="line">            totalDis += TSPData.disMap[curCity][nextCity];</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">this</span>.distance=totalDis;</span><br><span class="line">        <span class="keyword">this</span>.fitness=<span class="number">1.0f</span>/totalDis;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//深拷贝</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> SpeciesIndividual <span class="title">clone</span><span class="params">()</span></span></span><br><span class="line"><span class="function">    </span>&#123;   </span><br><span class="line">        SpeciesIndividual species=<span class="keyword">new</span> SpeciesIndividual();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//复制值</span></span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">0</span>;i&lt;<span class="keyword">this</span>.genes.length;i++)</span><br><span class="line">            species.genes[i]=<span class="keyword">this</span>.genes[i];</span><br><span class="line">        species.distance=<span class="keyword">this</span>.distance;</span><br><span class="line">        species.fitness=<span class="keyword">this</span>.fitness;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> species; </span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//打印路径</span></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">printRate</span><span class="params">()</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        System.out.print(<span class="string">"最短路线："</span>);</span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">0</span>;i&lt;genes.length;i++)</span><br><span class="line">            System.out.print(genes[i]+<span class="string">"-&gt;"</span>);</span><br><span class="line">        System.out.print(genes[<span class="number">0</span>]+<span class="string">"\n"</span>);</span><br><span class="line">        System.out.print(<span class="string">"最短长度："</span> + distance);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>SpeciesPopulation.java</strong></p>
<p>种群类，总群由物种组成。该类功能主要是把物种聚集起来形成总群的。我们姑且就当做一个物种只有一个个体。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> GeneticTSP;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 种群类</span></span><br><span class="line"><span class="comment"> * 包含：</span></span><br><span class="line"><span class="comment"> *         1.add 添加物种</span></span><br><span class="line"><span class="comment"> *         2.traverse 遍历</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SpeciesPopulation</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    SpeciesIndividual head;<span class="comment">//头结点</span></span><br><span class="line">    <span class="keyword">int</span> speciesNum;<span class="comment">//物种数量</span></span><br><span class="line"></span><br><span class="line">    SpeciesPopulation()</span><br><span class="line">    &#123;</span><br><span class="line">        head=<span class="keyword">new</span> SpeciesIndividual();</span><br><span class="line">        speciesNum=TSPData.SPECIES_NUM;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//添加物种</span></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">add</span><span class="params">(SpeciesIndividual species)</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        SpeciesIndividual point=head;<span class="comment">//游标</span></span><br><span class="line">        <span class="keyword">while</span>(point.next != <span class="keyword">null</span>)<span class="comment">//寻找表尾结点</span></span><br><span class="line">            point=point.next;</span><br><span class="line">        point.next=species;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//遍历</span></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">traverse</span><span class="params">()</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        SpeciesIndividual point=head.next;<span class="comment">//游标</span></span><br><span class="line">        <span class="keyword">while</span>(point != <span class="keyword">null</span>)<span class="comment">//寻找表尾结点</span></span><br><span class="line">        &#123;</span><br><span class="line">            <span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">0</span>;i&lt;TSPData.CITY_NUM;i++)</span><br><span class="line">                System.out.print(point.genes[i]+<span class="string">" "</span>);</span><br><span class="line">            System.out.println(point.distance);</span><br><span class="line">            point=point.next;</span><br><span class="line">        &#125;</span><br><span class="line">        System.out.println(<span class="string">"_______________________"</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>GeneticAlgorithm.java</strong></p>
<p>重头戏来了。下面重点介绍GA算法类中的几个方法：</p>
<ul>
<li><p>createBeginningSpecies</p>
<p>  创建种群，100%随机创建或者40%贪婪创建。40%贪婪创建就是40的物种采用贪婪算法生成基因。物种数由TSPData类中的物种数指定。</p>
</li>
</ul>
<ul>
<li><p>calRate</p>
<p>  计算每一物种被选中的概率。物种个体中的rate变量记录了该概率。</p>
</li>
</ul>
<ul>
<li><p>select</p>
<p>  轮盘制选择物种进行染色体交叉。这里的策略讲讲，我们的目标是选出优秀个体染色体交叉生成新的种群。然后再提一句，该方法只是选择个体而已，还没进行交叉操作。</p>
<p>  1) 我们先找出最大适应度的个体。然后复制该个体到新种群去，复制数量占原来种群的1/4。</p>
<p>  2) 然后新种群的3/4我们采用轮盘制选择，选择概率随机产生，毕竟大自然选择也是看天意的……然后每次选择那些，选中的概率（前面算出来了）大于或等于随机概率的个体，塞进新种群。注意边界处理。</p>
</li>
</ul>
<ul>
<li><p>crossover</p>
<p>  交叉操作，以一定的概率区间进行。详细说明一下步骤：</p>
<p>  1) 先随机找出两个个体（个体point和个体point.next）。</p>
<p>  2) 在一定的概率区间。对个体point和个体point.next进行如下操作：</p>
</li>
</ul>
<p>循环 i to city_num(i随机产生)</p>
<pre><code>找出point.genes中与point.next.genes[i]相等的位置fir

找出point.next.genes中与point.genes[i]相等的位置sec
</code></pre><p><img src="http://oyxhmjutw.bkt.clouddn.com/18-5-22/54041577.jpg" alt=""></p>
<p>然后执行如下交换操作：<br><img src="http://oyxhmjutw.bkt.clouddn.com/18-5-22/21277324.jpg" alt=""></p>
<p>直到结束循环</p>
<ul>
<li><p>mutate</p>
<p>  变异操作。每一种物种都有变异的可能，我们以一定概率进行。在这个TSP问题中，我们采用的变异操作其实跟迭代搜索那个two opt有点类似。在基因序列中，随机产生i~j的区间，然后将区间反转，形成新的染色体。很easy吧……</p>
</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br><span class="line">202</span><br><span class="line">203</span><br><span class="line">204</span><br><span class="line">205</span><br><span class="line">206</span><br><span class="line">207</span><br><span class="line">208</span><br><span class="line">209</span><br><span class="line">210</span><br><span class="line">211</span><br><span class="line">212</span><br><span class="line">213</span><br><span class="line">214</span><br><span class="line">215</span><br><span class="line">216</span><br><span class="line">217</span><br><span class="line">218</span><br><span class="line">219</span><br><span class="line">220</span><br><span class="line">221</span><br><span class="line">222</span><br><span class="line">223</span><br><span class="line">224</span><br><span class="line">225</span><br><span class="line">226</span><br><span class="line">227</span><br><span class="line">228</span><br><span class="line">229</span><br><span class="line">230</span><br><span class="line">231</span><br><span class="line">232</span><br><span class="line">233</span><br><span class="line">234</span><br><span class="line">235</span><br><span class="line">236</span><br><span class="line">237</span><br><span class="line">238</span><br><span class="line">239</span><br><span class="line">240</span><br><span class="line">241</span><br><span class="line">242</span><br><span class="line">243</span><br><span class="line">244</span><br><span class="line">245</span><br><span class="line">246</span><br><span class="line">247</span><br><span class="line">248</span><br><span class="line">249</span><br><span class="line">250</span><br><span class="line">251</span><br><span class="line">252</span><br><span class="line">253</span><br><span class="line">254</span><br><span class="line">255</span><br><span class="line">256</span><br><span class="line">257</span><br><span class="line">258</span><br><span class="line">259</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> GeneticTSP;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.Random;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 遗传算法类</span></span><br><span class="line"><span class="comment"> * 包含：</span></span><br><span class="line"><span class="comment"> *         1.run 开始跑算法</span></span><br><span class="line"><span class="comment"> *         2.createBeginningSpecies 创建种群</span></span><br><span class="line"><span class="comment"> *         3.calRate 计算每一种物种被选中的概率</span></span><br><span class="line"><span class="comment"> *      4.select  轮盘策略 选择适应度高的物种</span></span><br><span class="line"><span class="comment"> *      5.crossover 染色体交叉</span></span><br><span class="line"><span class="comment"> *      6.mutate 染色体变异</span></span><br><span class="line"><span class="comment"> *      7.getBest 获得适应度最大的物种</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">GeneticAlgorithm</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//开始遗传</span></span><br><span class="line">        <span class="function">SpeciesIndividual <span class="title">run</span><span class="params">(SpeciesPopulation list)</span></span></span><br><span class="line"><span class="function">        </span>&#123;</span><br><span class="line">            <span class="comment">//创建初始种群</span></span><br><span class="line">            createBeginningSpecies(list);</span><br><span class="line"></span><br><span class="line">            <span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">1</span>;i&lt;=TSPData.DEVELOP_NUM;i++)</span><br><span class="line">            &#123;</span><br><span class="line">                <span class="comment">//选择</span></span><br><span class="line">                select(list);</span><br><span class="line"></span><br><span class="line">                <span class="comment">//交叉</span></span><br><span class="line">                crossover(list);</span><br><span class="line"></span><br><span class="line">                <span class="comment">//变异</span></span><br><span class="line">                mutate(list);</span><br><span class="line">            &#125;   </span><br><span class="line"></span><br><span class="line">            <span class="keyword">return</span> getBest(list);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//创建初始种群</span></span><br><span class="line">        <span class="function"><span class="keyword">void</span> <span class="title">createBeginningSpecies</span><span class="params">(SpeciesPopulation list)</span></span></span><br><span class="line"><span class="function">        </span>&#123;</span><br><span class="line">            <span class="comment">//100%随机</span></span><br><span class="line">            <span class="keyword">int</span> randomNum=(<span class="keyword">int</span>)(TSPData.SPECIES_NUM);</span><br><span class="line">            <span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">1</span>;i&lt;=randomNum;i++)</span><br><span class="line">            &#123;</span><br><span class="line">                SpeciesIndividual species=<span class="keyword">new</span> SpeciesIndividual();<span class="comment">//创建结点</span></span><br><span class="line">                species.createByRandomGenes();<span class="comment">//初始种群基因</span></span><br><span class="line"></span><br><span class="line">                list.add(species);<span class="comment">//添加物种</span></span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//            //40%贪婪</span></span><br><span class="line"><span class="comment">//            int greedyNum=TSPData.SPECIES_NUM-randomNum;</span></span><br><span class="line"><span class="comment">//            for(int i=1;i&lt;=greedyNum;i++)</span></span><br><span class="line"><span class="comment">//            &#123;</span></span><br><span class="line"><span class="comment">//                SpeciesIndividual species=new SpeciesIndividual();//创建结点</span></span><br><span class="line"><span class="comment">//                species.createByGreedyGenes();//初始种群基因</span></span><br><span class="line">    <span class="comment">//</span></span><br><span class="line"><span class="comment">//                this.add(species);//添加物种</span></span><br><span class="line"><span class="comment">//            &#125;</span></span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//计算每一物种被选中的概率</span></span><br><span class="line">        <span class="function"><span class="keyword">void</span> <span class="title">calRate</span><span class="params">(SpeciesPopulation list)</span></span></span><br><span class="line"><span class="function">        </span>&#123;</span><br><span class="line">            <span class="comment">//计算总适应度</span></span><br><span class="line">            <span class="keyword">float</span> totalFitness=<span class="number">0.0f</span>;</span><br><span class="line">            list.speciesNum=<span class="number">0</span>;</span><br><span class="line">            SpeciesIndividual point=list.head.next;<span class="comment">//游标</span></span><br><span class="line">            <span class="keyword">while</span>(point != <span class="keyword">null</span>)<span class="comment">//寻找表尾结点</span></span><br><span class="line">            &#123;</span><br><span class="line">                point.calFitness();<span class="comment">//计算适应度</span></span><br><span class="line"></span><br><span class="line">                totalFitness += point.fitness;</span><br><span class="line">                list.speciesNum++;</span><br><span class="line"></span><br><span class="line">                point=point.next;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="comment">//计算选中概率</span></span><br><span class="line">            point=list.head.next;<span class="comment">//游标</span></span><br><span class="line">            <span class="keyword">while</span>(point != <span class="keyword">null</span>)<span class="comment">//寻找表尾结点</span></span><br><span class="line">            &#123;</span><br><span class="line">                point.rate=point.fitness/totalFitness;</span><br><span class="line">                point=point.next;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//选择优秀物种（轮盘赌）</span></span><br><span class="line">        <span class="function"><span class="keyword">void</span> <span class="title">select</span><span class="params">(SpeciesPopulation list)</span></span></span><br><span class="line"><span class="function">        </span>&#123;           </span><br><span class="line">            <span class="comment">//计算适应度</span></span><br><span class="line">            calRate(list);</span><br><span class="line"></span><br><span class="line">            <span class="comment">//找出最大适应度物种</span></span><br><span class="line">            <span class="keyword">float</span> talentDis=Float.MAX_VALUE;</span><br><span class="line">            SpeciesIndividual talentSpecies=<span class="keyword">null</span>;</span><br><span class="line">            SpeciesIndividual point=list.head.next;<span class="comment">//游标</span></span><br><span class="line"></span><br><span class="line">            <span class="keyword">while</span>(point!=<span class="keyword">null</span>)</span><br><span class="line">            &#123;</span><br><span class="line">                <span class="keyword">if</span>(talentDis &gt; point.distance)</span><br><span class="line">                &#123;</span><br><span class="line">                    talentDis=point.distance;</span><br><span class="line">                    talentSpecies=point;</span><br><span class="line">                &#125;</span><br><span class="line">                point=point.next;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="comment">//将最大适应度物种复制talentNum个</span></span><br><span class="line">            SpeciesPopulation newSpeciesPopulation=<span class="keyword">new</span> SpeciesPopulation();</span><br><span class="line">            <span class="keyword">int</span> talentNum=(<span class="keyword">int</span>)(list.speciesNum/<span class="number">4</span>);</span><br><span class="line">            <span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">1</span>;i&lt;=talentNum;i++)</span><br><span class="line">            &#123;</span><br><span class="line">                <span class="comment">//复制物种至新表</span></span><br><span class="line">                SpeciesIndividual newSpecies=talentSpecies.clone();</span><br><span class="line">                newSpeciesPopulation.add(newSpecies);</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="comment">//轮盘赌list.speciesNum-talentNum次</span></span><br><span class="line">            <span class="keyword">int</span> roundNum=list.speciesNum-talentNum;</span><br><span class="line">            <span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">1</span>;i&lt;=roundNum;i++)</span><br><span class="line">            &#123;</span><br><span class="line">                <span class="comment">//产生0-1的概率</span></span><br><span class="line">                <span class="keyword">float</span> rate=(<span class="keyword">float</span>)Math.random();</span><br><span class="line"></span><br><span class="line">                SpeciesIndividual oldPoint=list.head.next;<span class="comment">//游标</span></span><br><span class="line">                <span class="keyword">while</span>(oldPoint != <span class="keyword">null</span> &amp;&amp; oldPoint != talentSpecies)<span class="comment">//寻找表尾结点</span></span><br><span class="line">                &#123;</span><br><span class="line">                    <span class="keyword">if</span>(rate &lt;= oldPoint.rate)</span><br><span class="line">                    &#123;</span><br><span class="line">                        SpeciesIndividual newSpecies=oldPoint.clone();</span><br><span class="line">                        newSpeciesPopulation.add(newSpecies);</span><br><span class="line"></span><br><span class="line">                        <span class="keyword">break</span>;</span><br><span class="line">                    &#125;</span><br><span class="line">                    <span class="keyword">else</span></span><br><span class="line">                    &#123;</span><br><span class="line">                        rate=rate-oldPoint.rate;</span><br><span class="line">                    &#125;</span><br><span class="line">                    oldPoint=oldPoint.next;</span><br><span class="line">                &#125;</span><br><span class="line">                <span class="keyword">if</span>(oldPoint == <span class="keyword">null</span> || oldPoint == talentSpecies)</span><br><span class="line">                &#123;</span><br><span class="line">                    <span class="comment">//复制最后一个</span></span><br><span class="line">                    point=list.head;<span class="comment">//游标</span></span><br><span class="line">                    <span class="keyword">while</span>(point.next != <span class="keyword">null</span>)<span class="comment">//寻找表尾结点</span></span><br><span class="line">                        point=point.next;</span><br><span class="line">                    SpeciesIndividual newSpecies=point.clone();</span><br><span class="line">                    newSpeciesPopulation.add(newSpecies);</span><br><span class="line">                &#125;</span><br><span class="line"></span><br><span class="line">            &#125;</span><br><span class="line">            list.head=newSpeciesPopulation.head;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//交叉操作</span></span><br><span class="line">        <span class="function"><span class="keyword">void</span> <span class="title">crossover</span><span class="params">(SpeciesPopulation list)</span></span></span><br><span class="line"><span class="function">        </span>&#123;</span><br><span class="line">            <span class="comment">//以概率pcl~pch进行</span></span><br><span class="line">            <span class="keyword">float</span> rate=(<span class="keyword">float</span>)Math.random();</span><br><span class="line">            <span class="keyword">if</span>(rate &gt; TSPData.pcl &amp;&amp; rate &lt; TSPData.pch)</span><br><span class="line">            &#123;           </span><br><span class="line">                SpeciesIndividual point=list.head.next;<span class="comment">//游标</span></span><br><span class="line">                Random rand=<span class="keyword">new</span> Random();</span><br><span class="line">                <span class="keyword">int</span> find=rand.nextInt(list.speciesNum);</span><br><span class="line">                <span class="keyword">while</span>(point != <span class="keyword">null</span> &amp;&amp; find != <span class="number">0</span>)<span class="comment">//寻找表尾结点</span></span><br><span class="line">                &#123;</span><br><span class="line">                    point=point.next;</span><br><span class="line">                    find--;</span><br><span class="line">                &#125;</span><br><span class="line"></span><br><span class="line">                <span class="keyword">if</span>(point.next != <span class="keyword">null</span>)</span><br><span class="line">                &#123;</span><br><span class="line">                    <span class="keyword">int</span> begin=rand.nextInt(TSPData.CITY_NUM);</span><br><span class="line"></span><br><span class="line">                    <span class="comment">//取point和point.next进行交叉，形成新的两个染色体</span></span><br><span class="line">                    <span class="keyword">for</span>(<span class="keyword">int</span> i=begin;i&lt;TSPData.CITY_NUM;i++)</span><br><span class="line">                    &#123;</span><br><span class="line">                        <span class="comment">//找出point.genes中与point.next.genes[i]相等的位置fir</span></span><br><span class="line">                        <span class="comment">//找出point.next.genes中与point.genes[i]相等的位置sec</span></span><br><span class="line">                        <span class="keyword">int</span> fir,sec;</span><br><span class="line">                        <span class="keyword">for</span>(fir=<span class="number">0</span>;!point.genes[fir].equals(point.next.genes[i]);fir++);</span><br><span class="line">                        <span class="keyword">for</span>(sec=<span class="number">0</span>;!point.next.genes[sec].equals(point.genes[i]);sec++);</span><br><span class="line">                        <span class="comment">//两个基因互换</span></span><br><span class="line">                        String tmp;</span><br><span class="line">                        tmp=point.genes[i];</span><br><span class="line">                        point.genes[i]=point.next.genes[i];</span><br><span class="line">                        point.next.genes[i]=tmp;</span><br><span class="line"></span><br><span class="line">                        <span class="comment">//消去互换后重复的那个基因</span></span><br><span class="line">                        point.genes[fir]=point.next.genes[i];</span><br><span class="line">                        point.next.genes[sec]=point.genes[i];</span><br><span class="line"></span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//变异操作</span></span><br><span class="line">        <span class="function"><span class="keyword">void</span> <span class="title">mutate</span><span class="params">(SpeciesPopulation list)</span></span></span><br><span class="line"><span class="function">        </span>&#123;   </span><br><span class="line">            <span class="comment">//每一物种均有变异的机会,以概率pm进行</span></span><br><span class="line">            SpeciesIndividual point=list.head.next;</span><br><span class="line">            <span class="keyword">while</span>(point != <span class="keyword">null</span>)</span><br><span class="line">            &#123;</span><br><span class="line">                <span class="keyword">float</span> rate=(<span class="keyword">float</span>)Math.random();</span><br><span class="line">                <span class="keyword">if</span>(rate &lt; TSPData.pm)</span><br><span class="line">                &#123;</span><br><span class="line">                    <span class="comment">//寻找逆转左右端点</span></span><br><span class="line">                    Random rand=<span class="keyword">new</span> Random();</span><br><span class="line">                    <span class="keyword">int</span> left=rand.nextInt(TSPData.CITY_NUM);</span><br><span class="line">                    <span class="keyword">int</span> right=rand.nextInt(TSPData.CITY_NUM);</span><br><span class="line">                    <span class="keyword">if</span>(left &gt; right)</span><br><span class="line">                    &#123;</span><br><span class="line">                        <span class="keyword">int</span> tmp;</span><br><span class="line">                        tmp=left;</span><br><span class="line">                        left=right;</span><br><span class="line">                        right=tmp;</span><br><span class="line">                    &#125;</span><br><span class="line"></span><br><span class="line">                    <span class="comment">//逆转left-right下标元素</span></span><br><span class="line">                    <span class="keyword">while</span>(left &lt; right)</span><br><span class="line">                    &#123;</span><br><span class="line">                        String tmp;</span><br><span class="line">                        tmp=point.genes[left];</span><br><span class="line">                        point.genes[left]=point.genes[right];</span><br><span class="line">                        point.genes[right]=tmp;</span><br><span class="line"></span><br><span class="line">                        left++;</span><br><span class="line">                        right--;</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">                point=point.next;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//获得适应度最大的物种</span></span><br><span class="line">        <span class="function">SpeciesIndividual <span class="title">getBest</span><span class="params">(SpeciesPopulation list)</span></span></span><br><span class="line"><span class="function">        </span>&#123;</span><br><span class="line">            <span class="keyword">float</span> distance=Float.MAX_VALUE;</span><br><span class="line">            SpeciesIndividual bestSpecies=<span class="keyword">null</span>;</span><br><span class="line">            SpeciesIndividual point=list.head.next;<span class="comment">//游标</span></span><br><span class="line">            <span class="keyword">while</span>(point != <span class="keyword">null</span>)<span class="comment">//寻找表尾结点</span></span><br><span class="line">            &#123;</span><br><span class="line">                <span class="keyword">if</span>(distance &gt; point.distance)</span><br><span class="line">                &#123;</span><br><span class="line">                    bestSpecies=point;</span><br><span class="line">                    distance=point.distance;</span><br><span class="line">                &#125;</span><br><span class="line"></span><br><span class="line">                point=point.next;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">return</span> bestSpecies;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>以上就是遗传算法的java代码。</p>
<p>运行结果：</p>
<p>10个城市（最优解:147）<br><img src="http://oyxhmjutw.bkt.clouddn.com/18-5-11/31231208.jpg" alt=""></p>
<p>20个城市（最优解:870）</p>
<p><img src="http://oyxhmjutw.bkt.clouddn.com/18-5-11/83687057.jpg" alt=""></p>
<p>31个城市（最优解:14700）</p>
<p><img src="http://oyxhmjutw.bkt.clouddn.com/18-5-11/97346072.jpg" alt=""></p>
<p>最后在多说一句，这代码跑不出最优解也正常。启发式算法求近似解还是得靠人品的胸弟。</p>

    </div>

    <div class="post-footer">   
        <div>
            
                转载声明：商业转载请联系作者获得授权,非商业转载请注明出处 © <a href="" target="_blank">infinitor</a>
            
        </div>
        <div>
            
        </div>  
    </div>
</article>

<div class="article-nav prev-next-wrap clearfix">
    
        <a href="/2018/05/30/代码讲解/" class="pre-post btn btn-default"><i class="fa fa-angle-left fa-fw"></i>上一篇</a>
    
    
        <a href="/2018/05/22/遗传算法求解函数最值问题代码/" class="next-post btn btn-default">下一篇<i class="fa fa-angle-right fa-fw"></i></a>
    
</div>


    <div id="comments">
        
	
  <script id="dsq-count-scr" src="https://snippet.disqus.com/count.js" async></script>


<script type="text/javascript">
  var disqus_config = function () {
    this.page.url = 'http://yoursite.com/2018/05/22/超详细遗传算法(Genetic Algorithm)解析附带TSP代码/';
    this.page.identifier = '2018/05/22/超详细遗传算法(Genetic Algorithm)解析附带TSP代码/';
    this.page.title = '超详细遗传算法解析附带TSP代码';
  };
  var d = document, s = d.createElement('script');
  s.src = 'https://snippet.disqus.com/embed.js';
  s.setAttribute('data-timestamp', '' + +new Date());
  (d.head || d.body).appendChild(s);
</script>


	

    </div>





                </main>
                
    <aside class="col-md-4 sidebar">
        
        
    <div class="widget">    
        <h3 class="title">搜索</h3>
        <div id="search-form">
            <div id="result-mask" class="hide"></div>
            <div class="search-area">
                
                    <input id="search-key" type="search" autocomplete="off" placeholder="搜点什么呢?">
                    <button type="button" class="search-form-submit" id="search-local">站内搜索</button>
                
                
                    <form action="//google.com/search" method="get" accept-charset="UTF-8" class="search-form"><input type="search" name="q" class="search-form-input" placeholder="Google Search"><button type="submit" class="search-form-submit">谷歌搜索</button><input type="hidden" name="sitesearch" value="http://yoursite.com"></form>
                
            </div>
            <div id="result-wrap" class="hide">
                <div id="search-result"></div>
            </div>
            <div class="hide">
                <template id="search-tpl">
                    <div class="item">
                        <a href="/{path}" title="{title}">
                            <div class="title">{title}</div>
                            <div class="content">{content}</div>
                        </a>
                    </div>
                </template>
            </div>
        </div>
    </div>

        
        
    <div class="widget notification">
        <h3 class="title">网站公告</h3>
        <div>
            <p>大家好，欢迎来到我的个人博客。这里记录了我的成长过程，如果能帮到你一点点，我很开心。 <br/>
</p>
        </div>
    </div>

        
        
    <div class="widget">
      <h3 class="title">社交</h3> 
        <div class="content social">
            
	            <a href="//github.com/xiaoshiyisss" rel="external nofollow" title="Github" target="_blank">
			    	<i class="git fa fa-git"></i>
			    </a>
            
	            <a href="mailto:2638512393@qq.com" rel="external nofollow" title="邮箱" target="_blank">
			    	<i class="envelope-o fa fa-envelope-o"></i>
			    </a>
            
	            <a href="/" rel="external nofollow" title="联系QQ" target="_blank">
			    	<i class="qq fa fa-qq"></i>
			    </a>
            
	            <a href="/" rel="external nofollow" title="微博" target="_blank">
			    	<i class="weibo fa fa-weibo"></i>
			    </a>
            
	            <a href="/" rel="external nofollow" title="QQ群" target="_blank">
			    	<i class="users fa fa-users"></i>
			    </a>
            
	            <a href="/atom.xml" rel="external nofollow" title="RSS" target="_blank">
			    	<i class="feed fa fa-feed"></i>
			    </a>
            
        </div>
    </div>


        
        
    <div class="widget">
        <h3 class="title">分类</h3>
        <ul class="category-list"><li class="category-list-item"><a class="category-list-link" href="/categories/全栈/"><i class="fa" aria-hidden="true">全栈</i></a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/数据结构/"><i class="fa" aria-hidden="true">数据结构</i></a><span class="category-list-count">4</span></li><li class="category-list-item"><a class="category-list-link current" href="/categories/算法/"><i class="fa" aria-hidden="true">算法</i></a><span class="category-list-count">6</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/随想/"><i class="fa" aria-hidden="true">随想</i></a><span class="category-list-count">1</span></li></ul>
    </div>


        
        
    <div class="widget">
      <h3 class="title">归档</h3>
        <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/05/"><i class="fa" aria-hidden="true">May 2018</i></a><span class="archive-list-count">3</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/02/"><i class="fa" aria-hidden="true">February 2018</i></a><span class="archive-list-count">9</span></li></ul>
    </div>


        
        
  <div class="widget">
    <h3 class="title">标签云</h3>
    <div class="content tag-cloud">
        <a href="/tags/Python-游戏/" style="font-size: 10px;">Python, 游戏</a> <a href="/tags/数据结构/" style="font-size: 15px;">数据结构</a> <a href="/tags/算法/" style="font-size: 20px;">算法</a> <a href="/tags/随想/" style="font-size: 10px;">随想</a>
    </div>
  </div>


        
        
    <div class="widget">
        <h3 class="title">友链</h3>
        <div class="content friends-link">
        
            <a href="https://www.csdn.net/" class="fa" target="_blank">CSDN</a>
        
            <a href="https://www.cnblogs.com/" class="fa" target="_blank">博客园</a>
        
        </div>
    </div>


        
    </aside>

            </div>
        </div>
    </section>
    <footer class="main-footer">
    <div class="container">
        <div class="row">
        </div>
    </div>
</footer>

<a id="back-to-top" class="hide">
	<i class="fa fa-chevron-up"></i>
</a>




    <div class="copyright">
    <div class="container">
        <div class="row">
            <div class="col-sm-12"> 
                <span>Copyright &copy; 2017
                </span> | 
                <span>
                    Powered by <a href="//hexo.io" class="copyright-links" target="_blank" rel="nofollow">Hexo</a>
                </span> | 
                <span>
                    Theme by <a href="//github.com/shenliyang/hexo-theme-snippet.git" class="copyright-links" target="_blank" rel="nofollow">Snippet</a>
                </span>
            </div>
        </div>
    </div>
</div>



	<script src="/js/search.js?rev=@@hash"></script>


<script src="/js/app.js?rev=@@hash"></script>


</body>
</html>